package com.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author: sun.hongliang
 * @create: 2019/05/07 18:25
 */
public class MysqlTest {
    public static void main(String[] args) throws Exception {
        //声明Connection对象
        Connection con;
        //驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名mydata
        String url = "jdbc:mysql://10.211.5.5:3306/test";
        //MySQL配置时的用户名
        String user = "root";
        //MySQL配置时的密码
        String password = "123456";
        //遍历查询结果集
        Class.forName(driver);
        //1.getConnection()方法，连接MySQL数据库！！
        con = DriverManager.getConnection(url, user, password);
        if (!con.isClosed())
            System.out.println("Succeeded connecting to the Database!");
        //2.创建statement类对象，用来执行SQL语句！！
        Statement statement = con.createStatement();
        //要执行的SQL语句
        String sql = "select * from emp";
        //3.ResultSet类，用来存放获取的结果集！！
        ResultSet rs = statement.executeQuery(sql);
        System.out.println("-----------------");
        System.out.println("执行结果如下所示:");
        System.out.println("-----------------");
        System.out.println("姓名" + "\t" + "职称");
        System.out.println("-----------------");

        String job = null;
        String id = null;
        while (rs.next())

        {
            //获取stuname这列数据
            job = rs.getString("job");
            //获取stuid这列数据
            id = rs.getString("ename");

            //输出结果
            System.out.println(id + "\t" + job);
        }
        rs.close();
        con.close();
    }

}
